package com.llkj.qingnianguoxue.music;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.llkj.qingnianguoxue.R;
import com.llkj.qingnianguoxue.adapter.MusicLikeAdapter;
import com.llkj.qingnianguoxue.base.BaseFragment;
import com.llkj.qingnianguoxue.base.ConstantUserInfo;
import com.llkj.qingnianguoxue.base.MyApplication;
import com.llkj.qingnianguoxue.bean.CourseEvaluateBean;
import com.llkj.qingnianguoxue.bean.MusicLikeBean;
import com.llkj.qingnianguoxue.bean.response.ResponseList;
import com.llkj.qingnianguoxue.db.LocalMusicBean;
import com.llkj.qingnianguoxue.http.HttpMethod;
import com.llkj.qingnianguoxue.util.GsonUtil;
import com.llkj.qingnianguoxue.util.helper.LoadDataHelper;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.List;

/**
 * 我唱的
 */
public class MusicMineFragment extends BaseFragment implements BaseQuickAdapter.RequestLoadMoreListener,
        LoadDataHelper.LoadMoreListener, SwipeRefreshLayout.OnRefreshListener{

    protected SwipeRefreshLayout refreshLayout;
    protected RecyclerView lvMusicView;//
    private MusicLikeAdapter mMusicLikeAdapter;
    private List<MusicLikeBean> mMusicData;
    private int totalSize,mPage;
    private String mType;//1本地
    /**
     *
     */
    public static MusicMineFragment newInstance(String param) {
        MusicMineFragment fragment = new MusicMineFragment();
        Bundle args = new Bundle();
        args.putString("type", param);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_music_mine, container, false);

        setTitle("我喜欢", true, TITLE_TYPE_IMG, R.drawable.icon_back, false,-1,-1);
        mType = getArguments().getString("type");

        initView();
        initListener();
        getMusicData();
        return rootView;
    }

    private void initView(){
        refreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.refresh_layout);
        refreshLayout.setColorSchemeResources(R.color.blue3989ff);
        lvMusicView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
        lvMusicView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));

        mMusicData = new ArrayList<>();
        mMusicLikeAdapter = new MusicLikeAdapter(R.layout.item_music_like,mMusicData);
        lvMusicView.setAdapter(mMusicLikeAdapter);
    }

    private void getMusicData(){
        if("1".equals(mType)){
            refreshLayout.setEnabled(false);
            new QueryDataTask().execute();
        }else{
            loadWaitDialog();
            onRefresh();
        }
    }

    private void initListener(){
        refreshLayout.setOnRefreshListener(this);
        mMusicLikeAdapter.setOnLoadMoreListener(this);
        lvMusicView.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                MusicLikeBean item = mMusicData.get(i);
                Bundle bundle = new Bundle();
                if("1".equals(mType)){//保存本地的
                    bundle.putString("recordPath",item.getMp3());//录制文件地址
                }else{//已发布的
                    bundle.putString("recordPath",item.getSing());//录制文件地址
                }
                bundle.putString("musicLrcUrl",item.getLyric());//歌词链接
                bundle.putString("categoryType","1");
                bundle.putString("musicCoverUrl",item.getCoverUrl());//伴奏音乐封面图片
                bundle.putString("musicName",item.getName());//伴奏音乐名称
                bundle.putString("countSing",item.getSingCount());//演唱人数
                bundle.putString("musicBgPath",item.getBg_img());//背景图片地址
                startActivity(RecordCompleteActivity.class,bundle);
            }
        });
    }
    @Override
    public void onRefresh() {
        mPage = 1;
        getData();
    }
    @Override
    public void onLoadMore() {
        mPage++;
        getData();
    }

    private void getData(){
        String uid = MyApplication.getInstance().sputil.getString(ConstantUserInfo.USER_ID);
        String token = MyApplication.getInstance().sputil.getString(ConstantUserInfo.TOKEN);
        HttpMethod.kojiSing(getActivity(),this,uid,token,String.valueOf(mPage));
    }

    @Override
    protected void onhttpSuccess(String data, int method) {
        super.onhttpSuccess(data, method);
        refreshLayout.setRefreshing(false);
        if (HttpMethod.HTTP_KOJI_SING == method) {//
            ResponseList<MusicLikeBean> response = GsonUtil.fromJsonList(data,MusicLikeBean.class);
            if(response!=null){
                totalSize = Integer.parseInt(response.getNum());
                if (mPage == 1) {
                    mMusicData.clear();
                    LoadDataHelper.refreshComplete(mMusicLikeAdapter, mMusicData, refreshLayout, lvMusicView);
                } else {
                    mMusicLikeAdapter.setEnableLoadMore(true);
                    mMusicLikeAdapter.loadMoreComplete();
                }
                mMusicData.addAll(response.getLike());
                mMusicLikeAdapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    public void onLoadMoreRequested() {
        LoadDataHelper.loadMoreRequest(this, mMusicLikeAdapter, null, lvMusicView, totalSize);
    }

    /**
     * 数据库查询
     */
    class QueryDataTask extends AsyncTask<Void,Void,List<MusicLikeBean>>{

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            loadWaitDialog();
        }

        @Override
        protected List<MusicLikeBean> doInBackground(Void... voids) {
            List<LocalMusicBean> allNews = DataSupport.findAll(LocalMusicBean.class);
            List<MusicLikeBean> list = new ArrayList<>();
            MusicLikeBean likeBean = null;
            LocalMusicBean localMusicBean = null;
            for(int i=0;allNews!=null && i<allNews.size();i++){
                localMusicBean = allNews.get(i);
                likeBean = new MusicLikeBean();
                likeBean.setCoverUrl(localMusicBean.getMusicCorverUrl());
                likeBean.setSingCount(localMusicBean.getCountSing());
                likeBean.setTitle(localMusicBean.getMusicName());
                likeBean.setMp3(localMusicBean.getRecordMusicPath());
                likeBean.setBg_img(localMusicBean.getMusicBgPath());
                list.add(likeBean);
            }
            return list;
        }

        @Override
        protected void onPostExecute(List<MusicLikeBean> musicLikeBeans) {
            super.onPostExecute(musicLikeBeans);
            dismissWaitDialog();
            if(mMusicData!=null){
                mMusicData.addAll(musicLikeBeans);
                mMusicLikeAdapter.notifyDataSetChanged();
            }
        }
    }
}
